import requests
import json
import time

# 读取章节信息（上一脚本生成的结果文件）
with open("course_versions.json", "r", encoding="utf-8") as f:
    course_data = json.load(f)
with open ("Authorization.json", "r", encoding="utf-8") as f:
    Authorization = json.load(f)
    Token = Authorization['token']


url = "http://69.231.135.101/pgktstudent/student/JwOutlineDetail/getUserMessageForVideo"
headers = {
    "Accept": "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "Authorization": Token
}

result = {}

for course_name, chapters in course_data.items():
    result[course_name] = []
    for chapter in chapters:
        outline_id = chapter.get("outline_detail_id")
        version_id = chapter.get("version_id")
        payload = {
            "outlineId": outline_id,
            "versionId": version_id
        }
        # 防止空值
        if not outline_id or not version_id:
            print(f"课程《{course_name}》的章节《{chapter.get('version_name')}》缺少ID，跳过")
            continue
        try:
            resp = requests.post(url, headers=headers, data=json.dumps(payload), verify=False, timeout=10)
            if resp.status_code == 200:
                data = resp.json()
                if data.get("code") == 200 and "data" in data:
                    chapter_result = {
                        "chapter": chapter.get("chapter"),
                        "version_name": chapter.get("version_name"),
                        "version_id": version_id,
                        "outline_detail_id": outline_id,
                        "playPosition": data["data"].get("playPosition"),
                        "key": data["data"].get("key")
                    }
                    print(f"已获取《{course_name}》-《{chapter.get('version_name')}》的key")
                else:
                    chapter_result = {
                        "chapter": chapter.get("chapter"),
                        "version_name": chapter.get("version_name"),
                        "version_id": version_id,
                        "outline_detail_id": outline_id,
                        "playPosition": None,
                        "key": None,
                        "error": data.get("msg")
                    }
                    print(f"获取《{course_name}》-《{chapter.get('version_name')}》失败，msg: {data.get('msg')}")
            else:
                chapter_result = {
                    "chapter": chapter.get("chapter"),
                    "version_name": chapter.get("version_name"),
                    "version_id": version_id,
                    "outline_detail_id": outline_id,
                    "playPosition": None,
                    "key": None,
                    "error": f"HTTP {resp.status_code}"
                }
                print(f"HTTP错误：{resp.status_code}，课程《{course_name}》-《{chapter.get('version_name')}》")
        except Exception as e:
            chapter_result = {
                "chapter": chapter.get("chapter"),
                "version_name": chapter.get("version_name"),
                "version_id": version_id,
                "outline_detail_id": outline_id,
                "playPosition": None,
                "key": None,
                "error": str(e)
            }
            print(f"异常：{e}，课程《{course_name}》-《{chapter.get('version_name')}》")
        result[course_name].append(chapter_result)
        #time.sleep(1)  # 防止请求过快

# 保存结果到文件
with open("video_keys.json", "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)
print("全部完成，结果已保存到 video_keys.json")